package com.soloyogame.anitoys.pay.web.controller.front;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.PrintWriter;import java.text.DecimalFormat;import java.text.Format;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Properties;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import net.sf.json.JSONArray;import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.mvc.support.RedirectAttributes;import com.google.common.collect.Maps;import com.soloyogame.anitoys.db.bean.OrderCustInputInfo;import com.soloyogame.anitoys.db.bean.Spec;import com.soloyogame.anitoys.db.commond.Account;import com.soloyogame.anitoys.db.commond.AccountBuy;import com.soloyogame.anitoys.db.commond.AccountCoupon;import com.soloyogame.anitoys.db.commond.AccountFinance;import com.soloyogame.anitoys.db.commond.AccountPointsLog;import com.soloyogame.anitoys.db.commond.AccountSecurity;import com.soloyogame.anitoys.db.commond.Address;import com.soloyogame.anitoys.db.commond.Business;import com.soloyogame.anitoys.db.commond.BusinessShipping;import com.soloyogame.anitoys.db.commond.BusinessShippingDetail;import com.soloyogame.anitoys.db.commond.CartInfo;import com.soloyogame.anitoys.db.commond.Express;import com.soloyogame.anitoys.db.commond.Order;import com.soloyogame.anitoys.db.commond.Orderdetail;import com.soloyogame.anitoys.db.commond.Orderlog;import com.soloyogame.anitoys.db.commond.Orderpay;import com.soloyogame.anitoys.db.commond.Ordership;import com.soloyogame.anitoys.db.commond.PayInfo;import com.soloyogame.anitoys.db.commond.Product;import com.soloyogame.anitoys.db.commond.ProductStock;import com.soloyogame.anitoys.db.commond.SystemSetting;import com.soloyogame.anitoys.db.page.PagerModel;import com.soloyogame.anitoys.pay.web.util.LoginUserHolder;import com.soloyogame.anitoys.pay.web.util.RequestHolder;import com.soloyogame.anitoys.service.AccountBuyService;import com.soloyogame.anitoys.service.AccountCouponService;import com.soloyogame.anitoys.service.AccountFinanceService;import com.soloyogame.anitoys.service.AccountSecurityService;import com.soloyogame.anitoys.service.AddressService;import com.soloyogame.anitoys.service.BusinessService;import com.soloyogame.anitoys.service.ExpressService;import com.soloyogame.anitoys.service.HelpService;import com.soloyogame.anitoys.service.OrderBusinessShippingService;import com.soloyogame.anitoys.service.OrderService;import com.soloyogame.anitoys.service.OrderdetailService;import com.soloyogame.anitoys.service.OrderlogService;import com.soloyogame.anitoys.service.OrderpayService;import com.soloyogame.anitoys.service.OrdershipService;import com.soloyogame.anitoys.service.ProductService;import com.soloyogame.anitoys.service.SpecService;import com.soloyogame.anitoys.service.SystemSettingService;import com.soloyogame.anitoys.util.JsonUtil;import com.soloyogame.anitoys.util.KeyTool;import com.soloyogame.anitoys.util.PropertiesUtil;import com.soloyogame.anitoys.util.apiStore.ApiStore;import com.soloyogame.anitoys.util.apiStore.ApiStoreInfo;import com.soloyogame.anitoys.util.apiStore.ApiStoreItem;import com.soloyogame.anitoys.util.cache.RedisCacheProvider;import com.soloyogame.anitoys.util.constants.ManageContainer;import com.soloyogame.anitoys.util.email.Mail;import com.soloyogame.anitoys.util.email.SendCloud;import com.soloyogame.anitoys.util.front.FrontContainer;/** * 门户订单服务类 * * @author shaojian */@Controller("frontOrderAction")@RequestMapping("order")public class OrderAction extends FrontBaseController<Order> {    private static final Logger logger = LoggerFactory.getLogger(OrderAction.class);    private static final long serialVersionUID = 1L;    @Autowired    private OrderService orderService;    @Autowired    private OrderdetailService orderdetailService;    @Autowired    private OrderpayService orderpayService;    @Autowired    private ProductService productService;    @Autowired    private OrdershipService ordershipService;    @Autowired    private AddressService addressService;    @Autowired    private OrderBusinessShippingService orderBusinessShippingService;    @Autowired    private AccountCouponService accountCouponService;    @Autowired    private SpecService specService;    @Autowired    private OrderlogService orderlogService;    @Autowired    private BusinessService businessService;    @Autowired    private HelpService helpService;    @Autowired    private SystemSetting systemSetting;//20160402 注入systemSetting    @Autowired    private AccountBuyService accountBuyService;    @Autowired    private AccountFinanceService accountFinanceService;    @Autowired    private ExpressService expressService;    @Autowired    private RedisCacheProvider redisCacheProvider;    @Autowired    private SystemSettingService systemSettingService;    @Autowired    private AccountSecurityService accountSecurityService;    /**	 * 短信模板变量	 */    private static String lettermodel = "";        /**     * 发送站内消息模板     */    private static String messagemodel="";        protected static final String page_toLoginRedirect = "redirect:/account/login.html";    @Override    public OrderService getService() {        return orderService;    }    public void setOrderService(OrderService orderService) {        this.orderService = orderService;    }    /**     * 订单确认页面，点击这个页面的确认支付按钮则会跳转到支付宝等的支付页面     *     * @return     */    @RequestMapping("orderConfirm")    public String orderConfirm() {        logger.info("into method orderConfirm");        return "order/confirmOrder";    }    /**     * 从商品详情页面进入订单确认页面     *     * @param model     * @param request     * @return     * @author zhangjing     */    @RequestMapping(value = "toPlacPayFromDetail", method = RequestMethod.POST)    public String toPlacPayFromDetail(ModelMap model, HttpServletRequest request) {        //获得登陆用户信息，若获取空，则跳转登陆页面        Account account = getLoginAccount();        if (account == null || StringUtils.isBlank(account.getAccount())) {            return page_toLoginRedirect;        }        //获取前台传递商品id        String productID = request.getParameter("productId");            //商品ID        logger.info("productID = " + productID);        //获取前台传递购买数量        int buyCount = Integer.valueOf(request.getParameter("buyCount"));//购买数量        //获取前台传递选中的规格id        String buySpecID = request.getParameter("buySpecID");            //选中的规格ID        //若获取商品id为空或购买数量小于0，则抛出异常（“商品id传递失败！”）        if (StringUtils.isEmpty(productID) || buyCount < 0) {            throw new IllegalArgumentException("商品id传递失败！");        }        //根据商品id查询获取产品信息        Product product = productService.selectById(productID);        logger.info("现货/预售商品标识（1-现货，2-预售）：" + product.getProductType());        //将客户购买数量赋值        product.setBuyCount(buyCount);        /*         * 加载指定商品的规格信息		 */        if (StringUtils.isNotBlank(buySpecID)) {            //根据选中的规格id查询获取规格信息            Spec spec = specService.selectById(buySpecID);            if (spec == null) {                throw new NullPointerException("根据指定的规格" + buySpecID + "查询不到任何数据!");            }            //将匹配的规格信息赋值            product.setBuySpecInfo(spec);            //减少以后的逻辑判断，规格的价格等同于商品的价格            product.setNowPrice(spec.getSpecPrice());        }        //根据用户id获取用户配送地址列表        Address address = new Address();        address.setAccountId(account.getId());        List<Address> addressList = addressService.selectList(address);        logger.info("用户" + account.getAccount() + "共有" + addressList.size() + "个地址");        //将用户配送地址list传递前台        model.addAttribute("addressList", addressList);        model.addAttribute("addressListSize", addressList.size());        List<Order> sonOrderList = new ArrayList<Order>();    //子订单集合        Order sonOrder = new Order();    //子订单实体        //子订单商品总金额 = 商品购买数量 * 商品现价        sonOrder.setPtotal(Double.toString(product.getBuyCount() * Double.parseDouble(product.getNowPrice())));        //若商品为现货商品 ，标记子订单类型为现货        if (product.getProductType() == Order.PROD_TYPE_XIAN) {            sonOrder.setOrderType(Order.PROD_TYPE_XIAN); //现货            sonOrder.setRemark("现货商品订单");            //子订单总金额，此处暂时将商品总金额赋值，后会根据优惠、抵扣、运费等金额更新            sonOrder.setAmount(Double.toString(product.getBuyCount() *                    Double.parseDouble(product.getNowPrice())));//子订单总金额 -- 定金（子订单商品购买数量 * 商品现价）        }        //若商品为预售商品，标记子订单类型为预售        else if (product.getProductType() == Order.PROD_TYPE_YUSHOU) {            sonOrder.setOrderType(Order.PROD_TYPE_YUSHOU); //预售            sonOrder.setRemark("预售商品订单");            //子订单总金额，此处暂时将商品总金额赋值，后会根据优惠、抵扣、运费等金额更新            sonOrder.setAmount(Double.toString(product.getBuyCount() *                    Double.parseDouble(product.getDepositPrice())));//子订单总金额 -- 定金（子订单商品购买数量 * 商品预售价）            sonOrder.setAdvancePrice(Double.toString(product.getBuyCount() *                    Double.parseDouble(product.getDepositPrice())));//首付款 -- 定金（子订单商品购买数量 * 商品预售价）            sonOrder.setBalancePrice(Double.toString(Double.parseDouble(sonOrder.getPtotal()) -                    Double.parseDouble(sonOrder.getAdvancePrice())));//补款余额 -- 预售商品总价 - 首付款        }        //创建订单号        String orderCode = KeyTool.creatKey();        sonOrder.setOrderCode(orderCode);        sonOrder.setOrderCodeView(orderCode.substring(8));        /*         * 根据客户购买商品创建订单详情信息		 * 并赋值到子订单orderDetailList属性中		 * 因此方法是从商品详细页面进入，故一个子订单对应的是一个子订单详情		 */        List<Orderdetail> orderDetailList = new ArrayList<Orderdetail>();        Orderdetail orderdetail = createOrderDetail(product);        orderDetailList.add(orderdetail);        sonOrder.setOrderdetail(orderDetailList);        sonOrder.setQuantity(product.getBuyCount());        sonOrder.setAccount(account.getId());        //子订单所获积分 = 商品积分 * 购买数量        sonOrder.setScore(product.getScore() * product.getBuyCount());        sonOrder.setBusinessId(product.getBusinessId());        if (StringUtils.isNotBlank(product.getBusinessId())) {            //根据商品商家编号查询获取商家信息            Business business = businessService.selectById(product.getBusinessId());            sonOrder.setBusinessName(business.getBusinessName());        //子订单商家名称        }        //根据商家id获取配送方式list        List<BusinessShipping> businessShippingList =                orderBusinessShippingService.queryOrderBusinessShipping(product.getBusinessId());        sonOrder.setBusinessShippingList(businessShippingList);        /*         * 根据用户id和商家id获取用户有效优惠券list		 * 创建一个优惠券实体，表示用户不使用优惠券，并添加到list第一位，用于前台默认展示		 * 并将优惠券list赋值到子订单中		 */        List<AccountCoupon> accountCouponList =                accountCouponService.selectAccountCouponList(account.getId(), product.getBusinessId());        AccountCoupon accountCoupon = new AccountCoupon();        accountCoupon.setId("MF0001");        accountCoupon.setCouponName("未使用优惠券");        accountCoupon.setCouponValue("0.0");        accountCouponList.add(0, accountCoupon);        sonOrder.setAccountCouponList(accountCouponList);        //用于区分预售/现货商品子订单	0 -- 预售 1 -- 现货        sonOrder.setOrderFlag(0);        sonOrderList.add(sonOrder);        //将子订单list传递前台        model.addAttribute("sonOrderList", sonOrderList);        //根据用户信息和子订单list创建父订单信息        Order parentOrder = createParentOrder(account, sonOrderList);        /*         * 根据用户id获取用户平台抵扣券list		 * 创建一个抵扣券实体，表示用户不使用抵扣券，并添加到list第一位，用于前台默认展示		 * 并将抵扣券list赋值到父订单中		 */        List<AccountCoupon> accountVoucherList =                accountCouponService.selectAccountVoucherList(account.getId());        AccountCoupon accountVoucher = new AccountCoupon();        accountVoucher.setId("MFPT0001");        accountVoucher.setCouponName("未使用抵扣券");        accountVoucher.setCouponValue("0.0");        accountVoucherList.add(0, accountVoucher);        parentOrder.setAccountVoucherList(accountVoucherList);        //将父订单传递到前台        model.addAttribute("parentOrder", parentOrder);        //根据用户id获取用户积分信息        int rank = 0;        AccountFinance accountFinance =                accountFinanceService.queryAccountFinanceByUserId(account.getId());        if (accountFinance != null) {            rank = accountFinance.getRank();        }        //将用户积分传递前台        model.addAttribute("rank", rank);        //将父订单存入redis中，做后面逻辑使用        redisCacheProvider.put(account.getId() + "parentOrder", parentOrder);        //跳转到订单确认页面        return "order/plac";    }    /**     * 购物车进入订单确认页面，点击页面的去结算按钮进入订单确认页面     *     * @param model     * @param ids   购物车中用户勾选的付款商品id     * @return 跳转订单确认页面     * @author zhangjing     */    @RequestMapping("plac")    public String placPay(ModelMap model, String[] ids) {        //获得用户信息        Account account = getLoginAccount();        //若获取登录用户信息为null，则跳到登陆页面        if (account == null || StringUtils.isBlank(account.getAccount())) {            return page_toLoginRedirect;        }        //根据登陆用户id获取用户地址列表        Address address = new Address();        address.setAccountId(account.getId());        List<Address> addressList = addressService.selectList(address);        logger.info("用户" + account.getAccount() + "共有" + addressList.size() + "个地址");        //将用户地址list传递前台        model.addAttribute("addressList", addressList);        //获取用户选中的商品信列表（这里暂时生成一个临时的子订单，不进行插库）        List<Order> sonOrderList = this.createSonOrderInfo(account, ids);        logger.info("子订单个数：" + sonOrderList.size());        //将临时子订单传递前台        model.addAttribute("sonOrderList", sonOrderList);        //根据子订单生成临时父订单        Order parentOrder = this.createParentOrder(account, sonOrderList);        //根据用户id获取用户平台抵扣券list        List<AccountCoupon> accountVoucherList = accountCouponService.selectAccountVoucherList(account.getId());        //生成一个默认的抵扣券，表示用户未使用任何抵扣券        AccountCoupon accountCoupon = new AccountCoupon();        accountCoupon.setId("MFPT0001");        accountCoupon.setCouponName("未使用抵扣券");        accountCoupon.setCouponValue("0.0");        accountVoucherList.add(0, accountCoupon);        parentOrder.setAccountVoucherList(accountVoucherList);        //将父订单传递前台        model.addAttribute("parentOrder", parentOrder);        //将父订单信息存入radis缓存中，供后流程使用，注意绑定用户id//		if(redisCacheProvider.get(account.getId() + "parentOrder") != null) {//			redisCacheProvider.remove(account.getId() + "parentOrder");//		}        redisCacheProvider.put(account.getId() + "parentOrder", parentOrder);        //根据用户id获取用户积分信息        int rank = 0;        AccountFinance accountFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());        if (accountFinance != null) {            rank = accountFinance.getRank();        }        //将用户积分信息传递前台        model.addAttribute("rank", rank);        //跳转到订单确认页面        return "order/plac";    }    /**     * 生成子订单集合     *     * @param account 登陆用户信息     * @param ids     购物车中用户勾选的付款商品id     * @return List<Order> 子订单集合     * @author zhangjing     */    private List<Order> createSonOrderInfo(Account account, String[] ids) {        List<Order> sonOrderList = new ArrayList<Order>();        //子订单集合，既返回结果集        List<Product> productList = new ArrayList<Product>();        //用于存放购物车用户选中商品列表        //从redis中获取用户购物车中所有商品列表        CartInfo cartInfo = (CartInfo) redisCacheProvider.get("user_" + account.getId() + "Cart");        if (cartInfo == null || cartInfo.getProductList().size() == 0) {            throw new NullPointerException("用户购物车中没有可支付的商品!");        }        //若用户有选中商品付款，则将勾选商品放入productList，供后使用        if (ids != null && ids.length > 0) {            for (int i = 0; i < ids.length; i++) {                for (Iterator<Product> it = cartInfo.getProductList().iterator(); it.hasNext(); ) {                    Product p = it.next();                    if (p.getId().equals(ids[i])) {                        productList.add(p);                        break;                    }                }            }        }        //创建用于存放用户选择付款现货商品集合        List<Product> productXianList = new ArrayList<Product>();        for (Product product : productList) {            //logger.info("product.getBuySpecInfo().getId() = " + product.getBuySpecInfo().getId());            logger.info("商品（" + product.getId() + "）标识（1-现货，2-预售）：" + product.getProductType() +                    "\n" + "商家id = " + product.getBusinessId());            //若商品为现货            if (product.getProductType() == Order.PROD_TYPE_XIAN) {                productXianList.add(product);            }            //若为预售商品            else if (product.getProductType() == Order.PROD_TYPE_YUSHOU) {                //随机生成子订单号                String orderCode = KeyTool.creatKey();                //创建子订单实体                Order sonOrder = new Order();                sonOrder.setOrderCode(orderCode);                        //子订单号                sonOrder.setOrderCodeView(orderCode.substring(8));        //预防过长，只截取8位                sonOrder.setNumber(product.getBuyCount());                //子订单商品购买数量                sonOrder.setPtotal(Double.toString(product.getBuyCount() *                        Double.parseDouble(product.getNowPrice())));    //子订单商品总价（子订单商品购买数量 * 商品现价）                sonOrder.setQuantity(product.getBuyCount());            //子订单商品总数量                sonOrder.setAmount(Double.toString(product.getBuyCount() *                        Double.parseDouble(product.getDepositPrice())));//子订单总金额 -- 定金（子订单商品购买数量 * 商品预售价）                sonOrder.setAdvancePrice(Double.toString(product.getBuyCount() *                        Double.parseDouble(product.getDepositPrice())));//首付款 -- 定金（子订单商品购买数量 * 商品预售价）                sonOrder.setBalancePrice(Double.toString(Double.parseDouble(sonOrder.getPtotal()) -                        Double.parseDouble(sonOrder.getAdvancePrice())));//补款余额 -- 预售商品总价 - 首付款                sonOrder.setOrderType(Order.PROD_TYPE_YUSHOU);            //子订单类型                sonOrder.setAccount(account.getId());                    //子订单用户id                sonOrder.setScore(product.getScore());                    //子订单获赠的积分                sonOrder.setBusinessId(product.getBusinessId());        //子订单商家编号                if (!StringUtils.isBlank(product.getBusinessId())) {                    //根据商品商家编号查询获取商家信息                    Business business = businessService.selectById(product.getBusinessId());                    sonOrder.setBusinessName(business.getBusinessName());//子订单商家名称                }                sonOrder.setIsSaleorder(0);                                //是否售后订单                //根据商品商家编号获取商家配送方式list                List<BusinessShipping> businessShippingList = orderBusinessShippingService.queryOrderBusinessShipping(product.getBusinessId());                sonOrder.setBusinessShippingList(businessShippingList);    //子订单配送方式地址                //根据用户id和商家编号获取该用户在该商家的优惠券list                List<AccountCoupon> accountCouponList = accountCouponService.selectAccountCouponList(account.getId(), product.getBusinessId());                //生成一个默认的优惠券，表示用户未使用任何优惠券                AccountCoupon accountCoupon = new AccountCoupon();                accountCoupon.setId("MF0001");                accountCoupon.setCouponName("未使用优惠券");                accountCoupon.setCouponValue("0.0");                accountCouponList.add(0, accountCoupon);                sonOrder.setAccountCouponList(accountCouponList);        //子订单商家优惠券                sonOrder.setOrderFlag(0);                                //用于区分预售/现货商品子订单 0 -- 预售 1-- 现货                sonOrder.setLowStocks("y");                                //子订单库存状态                sonOrder.setRemark("预售商品订单");                            //子订单备注                //子订单详情列表                List<Orderdetail> orderDetailList = new ArrayList<Orderdetail>();                Orderdetail orderdetail = this.createOrderDetail(product);                orderDetailList.add(orderdetail);                sonOrder.setOrderdetail(orderDetailList);                sonOrder.setStatus(Order.order_status_init);            //子订单状态                sonOrderList.add(sonOrder);            }        }        //针对所有现货生成子订单 -- 同一个仓库的现售商品生成同一个子订单        if (productXianList.size() >= 1) {            while (true) {                List<Product> productSamBusiness = new ArrayList<Product>();        //用于存放同一商家的商品                //随机生成订单号                String orderCode = KeyTool.creatKey();                Product productXian = productXianList.get(productXianList.size() - 1);                List<Orderdetail> orderDetailList = new ArrayList<Orderdetail>();                Orderdetail orderdetail = this.createOrderDetail(productXian);                orderDetailList.add(orderdetail);                productSamBusiness.add(productXian);                productXianList.remove(productXianList.size() - 1);                int quantity = productXian.getBuyCount();        //商品个数                double ptotal = productXian.getBuyCount() * Double.parseDouble(productXian.getNowPrice());                int score = productXian.getScore();                for (int i = productXianList.size() - 1; i >= 0; i--) {                    if (productXian.getBusinessId().equals(productXianList.get(i).getBusinessId())) {                        quantity += productXianList.get(i).getBuyCount();                        ptotal += productXianList.get(i).getBuyCount() * Double.parseDouble(productXianList.get(i).getNowPrice());                        score += productXianList.get(i).getScore();                        Orderdetail orderdetailSam = this.createOrderDetail(productXianList.get(i));                        orderdetailSam.setOrderID(orderCode);                        orderDetailList.add(orderdetailSam);                        productSamBusiness.add(productXianList.get(i));                        productXianList.remove(i);                    }                }                logger.info("商品个数：" + quantity + "，结算商品总金额：" + ptotal);                Order sonOrder = new Order();    //子订单实体                sonOrder.setOrderCode(orderCode);                sonOrder.setOrderCodeView(orderCode.substring(8));                sonOrder.setPtotal(Double.toString(ptotal));                sonOrder.setQuantity(quantity);                sonOrder.setAmount(sonOrder.getPtotal());                sonOrder.setOrderType(Order.PROD_TYPE_XIAN); //现售                sonOrder.setAccount(account.getId());                sonOrder.setScore(score);                sonOrder.setRemark("现售商品订单");                sonOrder.setBusinessId(productXian.getBusinessId());                if (!StringUtils.isBlank(productXian.getBusinessId())) {                    Business business = businessService.selectById(productXian.getBusinessId());                    sonOrder.setBusinessName(business.getBusinessName());                }                sonOrder.setBusinessShippingList(orderBusinessShippingService.queryOrderBusinessShipping(productXian.getBusinessId()));                //优惠券                List<AccountCoupon> accountCouponList = accountCouponService.selectAccountCouponList(account.getId(), productXian.getBusinessId());                //logger.info("优惠券类型：" + accountCouponList.get(0).getCouponType());                AccountCoupon accountCoupon = new AccountCoupon();                accountCoupon.setId("MF0001");                accountCoupon.setCouponName("未使用优惠券");                accountCoupon.setCouponValue("0.0");                accountCouponList.add(0, accountCoupon);                sonOrder.setAccountCouponList(accountCouponList);                sonOrder.setOrderFlag(1);                sonOrder.setOrderdetail(orderDetailList);                sonOrder.setStatus(Order.order_status_init);                sonOrderList.add(sonOrder);                //为了退出无限循环                if (productXianList.size() == 0) {                    break;                }            }        }        return sonOrderList;    }    /**     * 创建父订单信息     *     * @param account      //登陆用户信息     * @param sonOrderList //子订单列表     * @return     * @author zhangjing     */    private Order createParentOrder(Account account, List<Order> sonOrderList) {        //创建大订单对象        Order pareOrder = new Order();        pareOrder.setOrders(sonOrderList);        pareOrder.setAccount(account.getId());        //随机生成订单号        String orderCode = KeyTool.creatKey();        pareOrder.setOrderCode(orderCode);        pareOrder.setOrderCodeView(orderCode.substring(8));        //计算商品总数量        int quantity = 0;        int score = 0;        double ptotal = 0;        //子订单商品总金额        double amount = 0;        //子订单总金额（区别预售）        for (Order sonOrder : sonOrderList) {            quantity += sonOrder.getQuantity();            score += sonOrder.getScore();            ptotal += Double.parseDouble(sonOrder.getPtotal());            amount += Double.parseDouble(sonOrder.getAmount());        }        pareOrder.setQuantity(quantity);        pareOrder.setScore(score);        pareOrder.setPtotal(Double.toString(ptotal));         //订单商品总金额        pareOrder.setStatus(Order.order_status_init);        pareOrder.setPaystatus(Order.order_paystatus_n);        //订单总金额 = 内存订单总金额 (初始默认大订单总金额 = 子订单商品总金额)        pareOrder.setAmount(Double.toString(amount));        if (sonOrderList.size() == 1) {            pareOrder.setRemark("1笔订单");        } else {            pareOrder.setRemark("合并|" + sonOrderList.size() + "笔订单");        }        /*         * 对金额进行格式化，防止出现double型数字计算造成的益出。		 */        DecimalFormat df = new DecimalFormat("0.00");        pareOrder.setAmount(df.format(Double.valueOf(pareOrder.getAmount())));//订单总金额        pareOrder.setPtotal(df.format(Double.valueOf(pareOrder.getPtotal())));//订单商品总金额        //pareOrder.setFee(df.format(Double.valueOf(pareOrder.getFee())));//订单总配送费        return pareOrder;    }    /**     * 创建订单明细信息     *     * @param product     * @return     * @author zhangjing     */    private Orderdetail createOrderDetail(Product product) {        logger.info("**** " + product.getId() + " || " + product.getProductWeight());        Orderdetail orderdetail = new Orderdetail();        orderdetail.setProductID(Integer.parseInt(product.getId()));        orderdetail.setProductName(product.getName());        orderdetail.setPrice(product.getNowPrice());        orderdetail.setNumber(product.getBuyCount());        orderdetail.setTotal0(Double.toString(Double.parseDouble(product.getNowPrice()) * product.getBuyCount()));        orderdetail.setSpecId(product.getSpecJsonString());        orderdetail.setSpecInfo(product.getIntroduce());        orderdetail.setGoodsStatus(product.getStatus());        orderdetail.setGoodsImg(product.getImages());        orderdetail.setFirstType(product.getFirstType());        orderdetail.setSecontType(product.getSecondType());        orderdetail.setDepositPrice(product.getDepositPrice());        orderdetail.setBalancePrice(product.getBalancePrice());        orderdetail.setGiftID(product.getGiftID());        //orderdetail.setScore(product.getScore());//活的赠送的积分        orderdetail.setPrice(product.getPicture());        orderdetail.setProductWeight(product.getProductWeight());        if (product.getBuySpecInfo() != null) {            //按照规格计算            orderdetail.setSpecInfo("规格一:" + product.getBuySpecInfo().getSpecSize() + "，规格二:" + product.getBuySpecInfo().getSpecColor());            orderdetail.setSpecId(product.getBuySpecInfo().getId());            orderdetail.setPagerSize(Integer.valueOf(product.getBuySpecInfo().getSpecSize()));            orderdetail.setSpecColor(product.getBuySpecInfo().getSpecColor());        }        return orderdetail;    }    /**     * 跳转立即支付页面     *     * @param model     * @return     * @throws Exception     * @author zhangjing     */    @SuppressWarnings({"unchecked", "static-access"})    @RequestMapping(value = "pay", method = RequestMethod.POST)    public void pay(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception {        logger.info("pay method start");        String intoType = request.getParameter("intoType");        String accountVoucher = request.getParameter("accountVoucher");        String parentAmount = request.getParameter("parentAmount");        String addressId = request.getParameter("addressId");        String point = request.getParameter("point");        String usedScore = request.getParameter("usedScore");        logger.info("accountVoucher = " + accountVoucher + ",parentAmount = " + parentAmount +                ",addressId = " + addressId + ",point = " + point + ",usedScore = " + usedScore);        Account account = LoginUserHolder.getLoginAccount();    //得到登录用户的信息        //购物车进入支付        if ("placPay".equals(intoType)) {            List<OrderCustInputInfo> list = new ArrayList<OrderCustInputInfo>();            String orderCust = request.getParameter("orderCust");            if (!orderCust.isEmpty()) {                JSONArray jsonArray = new JSONArray().fromObject(orderCust);                list = (List) JSONArray.toCollection(jsonArray, OrderCustInputInfo.class);            }            //获得大订单信息            Order parentOrder = (Order) redisCacheProvider.get(account.getId() + "parentOrder");            parentOrder.setSelectAddressID(addressId);            Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");            parentOrder.setCreatedate(format.format(new Date()));            parentOrder.setAddTime(new Date());            parentOrder.setAmount(parentAmount);            if (!StringUtils.isBlank(usedScore)) {                parentOrder.setIsUsePoint(1);                parentOrder.setAmountExchangeScore(Integer.parseInt(usedScore));            } else {                parentOrder.setIsUsePoint(0);                parentOrder.setAmountExchangeScore(0);            }            if (!StringUtils.isBlank(accountVoucher)) {                parentOrder.setDeductibleId(accountVoucher.split(",")[0]);                parentOrder.setDeductible(accountVoucher.split(",")[1]);            }            List<Order> sonOrderList = parentOrder.getOrders();    //子订单信息            for (Order sonOrder : sonOrderList) {                for (OrderCustInputInfo orderCustInputInfo : list) {                    logger.info(orderCustInputInfo.toString());                    if (sonOrder.getOrderCode().equals(orderCustInputInfo.getOrderCode())) {                        sonOrder.setCarry(orderCustInputInfo.getExpressCode());     //运送方式                        sonOrder.setExpressCode(orderCustInputInfo.getExpressCode());                        sonOrder.setExpressName(orderCustInputInfo.getExpressName());                        sonOrder.setFee(orderCustInputInfo.getFee());                        sonOrder.setOtherRequirement(orderCustInputInfo.getOtherRequirement());                        //sonOrder.setPtotal(orderCustInputInfo.getPtotal());                        sonOrder.setAmount(orderCustInputInfo.getPtotal());                        //sonOrder.setAdvancePrice(orderCustInputInfo.getPtotal());                        sonOrder.setIsSaleorder(0);                        if (null != orderCustInputInfo.getCouponsId() && !"".equals(orderCustInputInfo.getCouponsId())) {                            sonOrder.setCouponsId(orderCustInputInfo.getCouponsId().split(",")[0]);                            sonOrder.setCoupons(orderCustInputInfo.getCouponsId().split(",")[1]);                            sonOrder.setIsUserCoupons(1);                        } else {                            sonOrder.setIsUserCoupons(0);                        }                        sonOrder.setRefundStatus("0");      //退款状态  0-未退款 1--退款                    }                }            }            insertAndPay(parentOrder, model, response,parentAmount);        }        //待补款进入支付        else if ("placAdd".equals(intoType)) {            Order addOrder = (Order) redisCacheProvider.get(account.getId() + "addOrder");            addOrder.setAmount(parentAmount);            addOrder.setSelectAddressID(addressId);            if (StringUtils.isNotBlank(accountVoucher)) {                addOrder.setDeductibleId(accountVoucher.split(",")[0]);                addOrder.setDeductible(accountVoucher.split(",")[1]);            }            redisCacheProvider.put(account.getId() + "mainOrder", addOrder);        }    }    /**     * 创建订单，并跳转到支付页面让用户进行支付     * @param parentOrder     * @param model     * @param response     * @param parentAmount 订单实际支付的金额     * @throws Exception     */    private void insertAndPay(Order parentOrder, ModelMap model, HttpServletResponse response,String parentAmount) throws Exception     {        response.setContentType("application/xml;charset=utf-8");        logger.info("大订单ID：" + parentOrder.getOrderCode());        logger.info("SelectAddressID = " + parentOrder.getSelectAddressID());        //无地址信息，视为非法请求        if (StringUtils.isBlank(parentOrder.getSelectAddressID())) {            throw new NullPointerException("非法请求！");        }                //创建订单并插入到数据库        Order order = orderService.createOrder(parentOrder,parentAmount);		/*		 * 创建订单后，在用户购物车中剔除本次选中商品		 */        CartInfo cartInfo = getMyCart();        List<Order> sonOrderList = parentOrder.getOrders();        //所有子订单        logger.info("包含子订单个数：" + sonOrderList.size());        for (Order sonOrder : sonOrderList)         {            List<Orderdetail> orderdetail = sonOrder.getOrderdetail();            for (int i = 0; i < orderdetail.size(); i++)             {                if (cartInfo != null && cartInfo.getProductList() != null)                {                    for (Iterator<Product> it = cartInfo.getProductList().iterator(); it.hasNext(); )                     {                        Product p = it.next();                        if (p.getId().equals(Integer.toString(orderdetail.get(i).getProductID())))                         {                            it.remove();                            //重新计算总支付金额                            cartInfo.totalCacl();                        }                    }                }            }        }        Account account = LoginUserHolder.getLoginAccount();    //得到登录用户的信息        if (account == null)         {            redisCacheProvider.put("myCart", cartInfo);        }         else         {            redisCacheProvider.put("user_" + account.getId() + "Cart", cartInfo);        }        logger.info("into plac_pay.ftl");        //radis中删除本次下单信息        //redisCacheProvider.remove(account.getId() + "parentOrder");        redisCacheProvider.put(account.getId() + "mainOrder", order);    }    protected CartInfo getMyCart() {        //return (CartInfo) RequestHolder.getSession().getAttribute(FrontContainer.myCart);        Account account = LoginUserHolder.getLoginAccount();    //得到登录用户的信息        CartInfo cartInfo = null;        if (account == null) {            cartInfo = (CartInfo) redisCacheProvider.get("myCart");        } else {            cartInfo = (CartInfo) redisCacheProvider.get("user_" + account.getId() + "Cart");        }        return cartInfo;    }    /**     * @param model     * @return     * @author zhangjing     */    @RequestMapping(value = "plac_pay", method = RequestMethod.POST)    public String toPlacPay(ModelMap model) {        //查询帐户余额        Account account = getLoginAccount();        if (account == null || StringUtils.isBlank(account.getAccount())) {            return page_toLoginRedirect;        }        Order mainOrder = (Order) redisCacheProvider.get(account.getId() + "mainOrder");        AccountFinance aFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());        if (aFinance != null) {            model.addAttribute("accountAmount", aFinance.getAmount());        }        model.addAttribute("mainOrder", mainOrder);        //redisCacheProvider.remove("mainOrder");        return "order/plac_pay";    }    /**     * 进入补款订单确认页面     *     * @param model     * @return     * @author zhangjing     */    @RequestMapping("plac_add")    public String toAddPay(ModelMap model, @ModelAttribute("order") Order order1) {        //获得用户信息        Account account = getLoginAccount();        if (account == null || StringUtils.isBlank(account.getAccount())) {            return page_toLoginRedirect;        }        String orderId = RequestHolder.getRequest().getParameter("id");        logger.info("plac_add:orderId = " + orderId);        //根据id查询子订单信息        Order order = orderService.selectById(orderId);        order.setBusinessShippingList(orderBusinessShippingService.queryOrderBusinessShipping(order.getBusinessId()));        //优惠券        List<AccountCoupon> accountCouponList = accountCouponService.selectAccountCouponList(account.getId(), order.getBusinessId());        AccountCoupon accountCoupon = new AccountCoupon();        accountCoupon.setId("MF0001");        accountCoupon.setCouponName("未使用优惠券");        accountCoupon.setCouponValue("0");        accountCouponList.add(0, accountCoupon);        order.setAccountCouponList(accountCouponList);        order.setOrderCodeView(order.getOrderCode().substring(8));        //补款时，将子订单尾款赋值于订单金额字段        order.setAmount(order.getBalancePrice());        //平台抵扣券        List<AccountCoupon> accountVoucherList = accountCouponService.selectAccountVoucherList(account.getId());        AccountCoupon accountVoucher = new AccountCoupon();        accountVoucher.setId("MFPT0001");        accountVoucher.setCouponName("未使用抵扣券");        accountVoucher.setCouponValue("0");        accountVoucherList.add(0, accountVoucher);        order.setAccountVoucherList(accountVoucherList);        //根据子订单查询订单详情信息        Orderdetail qayOrderDetail = new Orderdetail();        qayOrderDetail.setOrderID(orderId);        Orderdetail orderDetail = orderdetailService.selectOne(qayOrderDetail);        logger.info("orderDetail.getPicture() = " + orderDetail.getPicture());        /*         * 加载指定商品的规格信息		 */        if (StringUtils.isNotBlank(orderDetail.getSpecId())) {            //根据选中的规格id查询获取规格信息            Spec spec = specService.selectById(orderDetail.getSpecId());            if (spec == null) {                throw new NullPointerException("根据指定的规格" + orderDetail.getSpecId() + "查询不到任何数据!");            }            //将匹配的规格信息赋值            orderDetail.setPagerSize(Integer.valueOf(spec.getSpecSize()));            orderDetail.setSpecColor(spec.getSpecColor());        }        model.addAttribute("orderDetail", orderDetail);        //用户积分        int rank = 0;        AccountFinance accountFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());        if (accountFinance != null) {            rank = accountFinance.getRank();        }        model.addAttribute("rank", rank);        //地址列表        Address address = new Address();        address.setAccountId(account.getId());        List<Address> addressList = addressService.selectList(address);        logger.info("用户" + account.getAccount() + "共有" + addressList.size() + "个地址");        model.addAttribute("addressList", addressList);        model.addAttribute("order", order);        redisCacheProvider.put(account.getId() + "addOrder", order);        return "order/plac_add";    }    /**     * 点击立即支付按钮，执行订单状态信息修改操作     *     * @author zhangjing     */    @RequestMapping("immediatelyPay")    public String immediatelyPay() {        logger.info("immediately pay start....");        String orderid = RequestHolder.getRequest().getParameter("orderid");        Account account = getLoginAccount();        Orderlog orderlog = new Orderlog();        orderlog.setOrderid(orderid);//订单ID        orderlog.setAccount(account.getAccount());//操作人账号        orderlog.setContent("支付成功");//日志内容        orderlog.setAccountType(Orderlog.orderlog_accountType_p);        //orderService.updateOrderStatusByConfirm(orderlog);        logger.info("pay success....");        return "order/paySuccess";    }    /**     * 点击我的订单页面的未付款的订单进行付款操作,则跳转到付款页面进行付款     *     * @return     */    @RequestMapping("toOrderPay")    public String toOrderPay() {        if (getLoginAccount() == null) {            return page_toLogin;        }        String id = RequestHolder.getRequest().getParameter("id");        if (StringUtils.isBlank(id)) {            throw new NullPointerException();        }        Order queryOrder = new Order();        queryOrder.setId(id);        Order order = orderService.selectOne(queryOrder);        logger.info("orderId=" + order.getId());        if (order == null) {            throw new NullPointerException("根据订单号查询不到订单信息！");        }        boolean ispayCreate = orderpayService.isOrderpayCreate(order.getId());        logger.debug("立即付款torderpay是否已创建：" + ispayCreate);        if (!ispayCreate) {            //创建支付记录对象            Orderpay orderpay = new Orderpay();            orderpay.setOrderid(order.getId());            orderpay.setPaystatus(Orderpay.orderpay_paystatus_n);            orderpay.setPayamount(Double.valueOf(order.getAmount()));            orderpay.setPaymethod(Orderpay.orderpay_paymethod_alipayescow);            int orderpayID = orderpayService.insert(orderpay);            logger.error("orderpayID=" + orderpayID);            order.setOrderpayID(String.valueOf(orderpayID));        }        //查询配送地址信息        RequestHolder.getRequest().setAttribute("payInfo", createPayInfo(order));        return "alipayapi";    }    @RequestMapping("rateSuccess")    public String rateSuccess(ModelMap model) {        Account acc = getLoginAccount();        if (acc == null) {            return page_toLogin;        }        logger.error("rateSuccess...");        CartInfo cartInfo = null;        List<Product> productList = new ArrayList<Product>();        if (acc == null) {            cartInfo = (CartInfo) redisCacheProvider.get("myCart");        } else {            cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");        }        if (cartInfo != null) {            productList = cartInfo.getProductList();        } else {            cartInfo = new CartInfo();        }        int productCount = productService.selectProductCount();        model.addAttribute("cartInfo", cartInfo);        model.addAttribute("productCount", productCount);        model.addAttribute("productList", productList);        return "order/rateSuccess";    }    public void bcopy(File f1, File f2) {        if (f1.exists()) {            // 判断要拷贝的文件是否存在            copy(f1, f2);//调用copy方法            System.out.println("上传文件相关的信息：（名字，路径，大小，最后修改的时间是：）");            getinfo(f1);            getinfo(f2);            System.out.println("上传成功后文件相关的信息：（名字，路径，大小，最后修改的时间是：）");        } else {            System.out.println("要拷贝的文件不存在!");        }    }    //获取文件的一些信息    private void getinfo(File f1) {        // TODO Auto-generated method stub        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日hh时mm分ss秒");        if (f1.isFile()) {            //isFile()方法是测试此抽象路径名表示的文件是否是一个标准文件。            System.out.println("文件名称：" + f1.getName());            System.out.println("文件路径：" + f1.getAbsolutePath());            System.out.println("文件大小：" + f1.length() + "字节(byte)");            System.out.println("最后修改的时间是：" + sdf.format(new Date(f1.lastModified())));        } else {            System.out.println("上传成功后获取服务器的相关信息：");            System.out.println("目录名称：" + f1.getName());            System.out.println("文件路径：" + f1.getAbsolutePath());            File[] files = f1.listFiles();            System.out.println("此目录中有" + files.length + "个文件！");        }        System.out.println("_______________________________");    }    void copy(File f1, File f2) {//f1 源文件路径  f2目标路径   最后把f2 insert 到数据库就不写了        try {            // 建立相关的字节输入流            FileInputStream fr = new FileInputStream(f1); // 通过打开一个到实际文件的连接来创建一个            // FileInputStream，该文件通过文件系统中的路径名            // 创建一个向具有指定名称的文件中写入数据的输出文件流。            FileOutputStream fw = new FileOutputStream(f2);            byte buffer[] = new byte[1]; // 声明一个byte型的数组，数组的大小是512个字节            while (fr.read(buffer) != -1) { // read()从此输入流中读取一个数据字节，只要读取的结果不！=-1就执行while循环中的语句块                fw.write(buffer); //write(byte[] b)将 b.length 个字节从指定字节数组写入此文件输出流中。            }            fw.close();// 关闭此文件输出流并释放与此流有关的所有系统资源。            fr.close();            System.out.println("文件" + f1.getName() + "里的内容已拷贝到文件"                    + f2.getName() + "中！");        } catch (IOException ioe) {            System.out.println(ioe);        } catch (Exception e) {            System.out.println(e);        }    }    DecimalFormat df = new DecimalFormat("0.00");    /**     * 创建支付宝的付款信息对象     *     * @param order     */    private PayInfo createPayInfo(Order order) {        if (order == null) {            throw new NullPointerException("参数不能为空！请求非法！");        }        PayInfo payInfo = new PayInfo();        systemSetting = systemSettingService.selectOne(new SystemSetting());        String www = systemSetting.getWww();        /**         * 解决由于本地和线上正式环境提交相同的商户订单号导致支付宝出现TRADE_DATA_MATCH_ERROR错误的问题。         * 本地提交的商户订单号前缀是test开头，正式环境提交的就是纯粹的支付订单号         */        if (www.startsWith("http://127.0.0.1") || www.startsWith("http://localhost")) {            payInfo.setWIDout_trade_no("test" + order.getOrderCode());        } else {            payInfo.setWIDout_trade_no(order.getOrderCode());        }        payInfo.setWIDsubject(order.getProductName());        payInfo.setWIDprice(Double.valueOf(order.getAmount()));        payInfo.setWIDbody(order.getRemark());        payInfo.setShow_url(systemSetting.getWww() + "/order/orderInfo.html?id=" + order.getId());        payInfo.setWIDsubject(order.getRemark());        payInfo.setLogistics_fee(Double.valueOf(order.getFee()));        payInfo.setLogistics_type(order.getExpressCode());        logger.error(payInfo.toString());        return payInfo;    }    /**     * 查询我的订单列表信息     */    @RequestMapping("selectList")    public String selectList(HttpServletRequest request, @ModelAttribute("e") Order e, ModelMap model) throws Exception {        int offset = 0;//分页偏移量        if (request.getParameter("pager.offset") != null) {            offset = Integer                    .parseInt(request.getParameter("pager.offset"));        }        if (offset < 0)            offset = 0;        e.setOffset(offset);        PagerModel pager = getService().selectPageList(e);        if (pager == null) {            pager = new PagerModel();        }        // 计算总页数        pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)                / pager.getPageSize());        pager.setPagerUrl("myCarts");        model.addAttribute("pager", pager);        return "/account/orders";    }    /**     * 删除我的订单信息     */    @RequestMapping("deletes")    public String deletes(String[] ids, HttpServletRequest request, @ModelAttribute("e") Order e, ModelMap model) throws Exception {        getService().deletes(ids);        return selectList(request, e, model);    }    /**     * 退订或取消指定的订单     *     * @return     * @throws Exception     */    @RequestMapping("cancel")    public String cancel() throws Exception {        return "";    }    /**     * 读取指定订单的信息     *     * @return     */    @RequestMapping("read")    public String read() {        return "";    }    /**     * 对指定的订单进行支付     * @return     *///	public String doPay(){//		if(1==1){//			throw new NullPointerException();//		}//		//		String orderID = getRequest().getParameter("orderID");//		e.clear();//		e.setId(orderID);//		e.setStatus(Order.order_status_init);//等待付款//		logger.error("orderid=" + orderID);//		orderService.update(e);//		return "doPay";//	}    /**     * 查看订单详情     *     * @return     */    @RequestMapping("{orderId}")    public String orderDetail(@PathVariable("orderId") String id, ModelMap model) {        Account acc = getLoginAccount();        if (acc == null) {            return page_toLogin;        }        List<Product> productList = new ArrayList<Product>();        CartInfo cartInfo = null;        if (acc == null) {            cartInfo = (CartInfo) redisCacheProvider.get("myCart");        } else {            cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");        }        if (cartInfo != null) {            productList = cartInfo.getProductList();        } else {            cartInfo = new CartInfo();        }        int productCount = productService.selectProductCount();        model.addAttribute("cartInfo", cartInfo);        model.addAttribute("productCount", productCount);        model.addAttribute("productList", productList);        logger.error("orderInfo...");        if (StringUtils.isBlank(id)) {            throw new NullPointerException("订单ID不能为空！");        }        //查询订单信息        Order order = new Order();        order.setId(id);        order.setAccount(acc.getId());        List<Order> orders = orderService.selectOrderInfo(order);        if (orders == null || orders.size() == 0) {            throw new NullPointerException("根据订单ID查询不到订单信息！");        }        //商品规格        for (Order order2 : orders) {            if (!StringUtils.isBlank(order2.getSpecInfo()) && order2.getSpecInfo().indexOf(",") > 0) {                order2.setSpecInfo(order2.getSpecInfo().replace(",", "<br />"));                logger.debug("-------SpecInfo----------" + order2.getSpecInfo());            }        }        logger.error("orders.size=" + orders.size());        Order e = orders.get(0);        logger.debug("-----------------order 转换前t_order.status = " + e.getStatus());        //失效订单状态处理        logger.debug("-----------------失效订单状态处理 InitStatus = " + e.getInitStatus() + "  PassStatus = " + e.getPassStatus() + "  ExpiredTime = " + e.getExpiredTime());        if (!StringUtils.isBlank(e.getInitStatus()) || !StringUtils.isBlank(e.getPassStatus()) || e.getExpiredTime() != null) {            e.setStatus(com.soloyogame.anitoys.db.commond.Order.order_status_cancel);        }        logger.debug("-----------------order 转换后t_order.status = " + e.getStatus());        e.setOrders(orders);        //查询订单配送信息        Ordership ordership = new Ordership();        ordership.setOrderid(id);        ordership = ordershipService.selectOne(ordership);        if (ordership == null) {            ordership = new Ordership();            //throw new NullPointerException("根据订单ID查询不到订单配送信息！");        }        e.setOrdership(ordership);        //查询订单物流信息        //e.setKuaid100Info(kuaidi100Helper.selectKuaidi100());        model.addAttribute("e", e);        //订单跟踪日志        Orderlog odlog = new Orderlog();        odlog.setOrderid(id);        model.addAttribute("logList", orderlogService.selectList(odlog));        //查询使用积分        AccountPointsLog pointsLog = new AccountPointsLog();        pointsLog.setUserId(e.getAccount());        pointsLog.setOrderId(e.getParentId());        List<AccountPointsLog> pointsLogList = orderService.selectOrderPoints(pointsLog);        double rankCount1 = 0;        double rankCount2 = 0;        if (pointsLogList != null && pointsLogList.size() > 0) {            rankCount1 = pointsLogList.get(0).getRankCount();            if (pointsLogList.size() > 1) {                rankCount2 = pointsLogList.get(1).getRankCount();            }        }        logger.debug("订单详情，订单使用积分详情：订单编号ParentId：" + e.getParentId() + ",有count=" + pointsLogList.size() + "条订单积分使用详情");                        //订单支付日志        List payList = new ArrayList();        Map mp = null;//				if(e.getPayTime() != null || !StringUtils.isBlank(e.getAdvancePrice()) || e.getScore() >0 || !StringUtils.isBlank(e.getCoupons()) || !StringUtils.isBlank(e.getDeductible())){        if (e.getPayTime() != null) {            mp = new HashMap();            mp.put("score", rankCount1);            mp.put("payTime", e.getPayTime());            mp.put("advancePrice", e.getAdvancePrice());            if (!StringUtils.isBlank(e.getCoupons())) {                mp.put("coupons", e.getCoupons());            } else {                mp.put("coupons", e.getDeductible());            }            payList.add(mp);        }        if (e.getReplenishmentTime() != null) {            // && e.getOrderType() == 1            mp = new HashMap();            mp.put("score", rankCount2);            mp.put("payTime", e.getReplenishmentTime());            mp.put("advancePrice", e.getAdvancePrice());            if (!StringUtils.isBlank(e.getCoupons())) {                mp.put("coupons", e.getCoupons());            } else {                mp.put("coupons", e.getDeductible());            }            payList.add(mp);        }        model.addAttribute("payList", payList);        return "/account/orderDetail";    }    /**     * 查看物流信息     *     * @return     */    @RequestMapping("orderhipInfo")    public String orderhipInfo() {        logger.error("orderhipInfo...");        return "/account/orderhipInfo";    }    /**     * 确认订单信息     *     * @return     */    @RequestMapping("confirmOrder")    public String confirmOrder(ModelMap model) {        logger.error("confirmOrder..");        Account acc = getLoginAccount();        if (acc == null || StringUtils.isBlank(acc.getAccount())) {//			getSession().getAttribute(FrontContainer);            return page_toLoginRedirect;        }        //检查购买的商品是否超出可购买的库存数        CartInfo cartInfo = getMyCart();        if (cartInfo == null) {            throw new NullPointerException("非法请求");        }//        for (int i = 0; i < cartInfo.getProductList().size(); i++) {//            Product product = cartInfo.getProductList().get(i);//            ProductStockInfo stockInfo = SystemManager.getInstance().getProductStockMap().get(product.getId());//            if (stockInfo == null) {//                //商品已卖完或已下架，请联系站点管理员!//                throw new RuntimeException("商品已卖完或已下架，请联系站点管理员!");//            } else if (stockInfo.getStock() < product.getBuyCount()) {//                //购买的商品数超出库存数//                throw new RuntimeException("商品已卖完或已下架，请联系站点管理员!");//            }//        }        //加载配送信息        Address add = new Address();        add.setAccountId(acc.getAccount());        List<Address> addressList = addressService.selectList(add);        cartInfo.setAddressList(addressList);        if (addressList != null && addressList.size() > 0) {//			boolean exist = false;            for (int i = 0; i < addressList.size(); i++) {                Address addItem = addressList.get(i);                if (StringUtils.isNotBlank(addItem.getIsdefault()) && addItem.getIsdefault().equals("y")) {                    cartInfo.setDefaultAddessID(addItem.getId());                    break;                }            }        }        model.addAttribute("myCart", cartInfo);        model.addAttribute("expressList", loadExpress().values());        return "order/confirmOrder";    }    /**     * 加载物流列表     */    private Map<String, Express> loadExpress() {        List<Express> expressList = expressService.selectList(new Express());        Map<String, Express> expressMap = Maps.newHashMap();        if (expressList != null && expressList.size() > 0) {            for (int i = 0; i < expressList.size(); i++) {                Express item = expressList.get(i);                expressMap.put(item.getCode(), item);            }        }        return expressMap;    }    /**     * 支付成功后，回调请求跳转到的页面     * @return     */    @RequestMapping(value = "paySuccess")    public String paySuccess(ModelMap model)     {        Account acc = getLoginAccount();        logger.error("paySuccess...");        HttpSession session = RequestHolder.getRequest().getSession();        double payAmount;        String orderCode = String.valueOf(session.getAttribute("orderCode"));  //获得订单号        String payWay =  String.valueOf(session.getAttribute("payWay"));       //得到支付方式        String koukucunflagkey = orderCode+"_kouflag";                         //(1:已经刷新库存0：没有刷库存)        //根据订单号查询出订单信息        Order queryOrder = new Order();        queryOrder.setOrderCode(orderCode);        Order order = orderService.selectFrontOne(queryOrder);        /*         * 查询该单配送方式，获取配送地址，供支付成功页面展示		 * 并且进行支付成功后的一系列数据更新及插入操作		 * 因orderService.updateInfoAfterPay方法参数为父订单		 * 所以第一次付款订单和补款的预售单支付成功后更新相关信息传值有所不同		 * 	第一次付款订单 --> 父订单		 * 	补款的预售单 --> 子订单		 */        List<Orderdetail> orderdetailList = new LinkedList<Orderdetail>();        //根据父订单号查询获得子订单list        Order qrySonOrder = new Order();        qrySonOrder.setOrderCode(orderCode);        List<Order> sonOrderList = orderService.selectSonOrderList(qrySonOrder);        Orderdetail orderdetail = new Orderdetail();        for (Order order2 : sonOrderList)         {            orderdetail.setOrderID(order2.getId());            List<Orderdetail> list = orderdetailService.selectList(orderdetail);            orderdetailList.addAll(list);            //给客户发送邮件(发送绑定的邮箱)            if(redisCacheProvider.get(koukucunflagkey)==null)            {            	AccountSecurity accountSecurity = new AccountSecurity();            	accountSecurity.setUserId(acc.getId());            	accountSecurity = accountSecurityService.selectOne(accountSecurity);            	acc.setEmail(accountSecurity.getEmail());            	//支付成功发送邮件    	        sendMail(acc,order2);    	            	        //TODO 支付成功发送短信（等我那个张杰给模板）    	            	            	        //TODO 支付成功发送消息            }        }        Ordership qryOrderShip = new Ordership();        //存放查询配送信息条件        //若支付时间不为空，且订单类型为2，则表示该单为补款的预售单        if (order.getPayTime() != null && order.getOrderType() == 2) {            //因为补款单即为子订单，则可直接用订单id作为配送信息查询条件            qryOrderShip.setOrderid(order.getId());        }        //第一次从支付页面支付的主单（父订单）        else {            //若子订单list不为空，则取出第一条子订单id作为配送信息查询条件            if (sonOrderList.size() > 0) {                qryOrderShip.setOrderid(sonOrderList.get(0).getId());            }        }        //根据子订单id查询出配送信息        logger.info("qryOrderShip.getOrderid() = " + qryOrderShip.getOrderid());        Ordership orderShip = orderService.selectOrdership(qryOrderShip);//        session.setAttribute("orderShip", JSON.toJSONString(orderShip));        payAmount = Double.parseDouble(order.getAmount());        java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");        model.put("payAmount", df.format(payAmount));        System.out.println(df.format(payAmount));        model.put("orderShip", orderShip);               if(redisCacheProvider.get(koukucunflagkey)==null)        {	        //支付成功扣库存,刷新限购数量	        for (Orderdetail orderDetail : orderdetailList) 	        {	            //刷新缓存支付库存	            String specId = orderDetail.getSpecId();	            //刷新数据库的支付库存	            Spec s = specService.selectById(specId);	            s.setSpecStock(String.valueOf(Integer.valueOf(s.getSpecStock()) - orderDetail.getNumber()));	            s.setId(specId);	            specService.update(s);            	//支付成功刷新缓存客户购买数量                String account_product_xgsl = acc.getAccountId() + ManageContainer.account_product_xgsl + orderDetail.getProductID();                if (redisCacheProvider.get(account_product_xgsl) == null)                 {                    redisCacheProvider.put(account_product_xgsl, orderDetail.getNumber());                }                 else                 {                    Integer account_product_xgslValue = Integer.valueOf(redisCacheProvider.get(account_product_xgsl).toString());                    redisCacheProvider.put(account_product_xgsl, account_product_xgslValue + orderDetail.getNumber());                }                //支付成功刷新数据库的客户的购买数量                AccountBuy accountBuyParam = new AccountBuy();                accountBuyParam.setAccountId(acc.getId());                accountBuyParam.setProductId(orderDetail.getProductID());                AccountBuy accountBuy = accountBuyService.selectOne(accountBuyParam);                if (accountBuy == null)                 {                    accountBuy = new AccountBuy();                    accountBuy.setAccountId(acc.getId());                    accountBuy.setProductId(orderDetail.getProductID());                    accountBuy.setBuyNum(orderDetail.getNumber());                    accountBuyService.insert(accountBuy);                }                 else                 {                    accountBuy.setBuyNum(accountBuy.getBuyNum() + orderDetail.getNumber());                    accountBuyService.update(accountBuy);                }                //刷新销量和库存                Product productParam = productService.selectById(String.valueOf(orderDetail.getProductID()));                productParam.setAddSellcount(orderDetail.getNumber());                productParam.setStock(productParam.getStock()-orderDetail.getNumber());                productService.updateStockAfterPaySuccess(productParam);                redisCacheProvider.put(koukucunflagkey,"1");            }        }        return "order/paySuccess";    }        /**	 * 下单成功发送邮件	 * @param email	 * @param acc	 * @param vcode	 */	private void sendMail(Account acc,Order order) 	{		Properties  properties = PropertiesUtil.findCommonPro("config.properties");		final String url = properties.getProperty("mailUrl");		final String apiUser = properties.getProperty("apiUser");		final String apiKey = properties.getProperty("apiKey");		final String from = properties.getProperty("from");		final String fromname = properties.getProperty("fromname");		final String templateInvokeName = properties.getProperty("email_pay_success");		Mail mail = new Mail();		mail.setUrl(url);		mail.setApiKey(apiKey);        		mail.setApiUser(apiUser);		mail.setSender(from);		mail.setName(fromname);                                             //发件人地址		mail.setReceiver(acc.getEmail());    							    //收件人地址		mail.setSubject("Anitoys提醒:" + acc.getAccount() + "下单成功");     //邮件主题		mail.setTemplateInvokeName(templateInvokeName);		systemSetting = systemSettingService.selectOne(new SystemSetting());		mail.setWebName(systemSetting.getName());		mail.setSendTime(new Date());		mail.setOrderCode(order.getOrderCode());		mail.setOrderUrl(systemSetting.getMy()+"/order/"+order.getId());		mail.setReceiverName(acc.getAccount());		try 		{			SendCloud.send_template(mail);		}		catch (IOException e) 		{			e.printStackTrace();		}	}    /**     * 确认成功时跳转     *     * @param model     * @return     */    @RequestMapping("paySuccessAgain") //-_-!    public String paySuccessAgain(ModelMap model) {        return "order/paySuccess";    }    /**     * 订单中心 - 确认收货     *     * @return     */    @RequestMapping("confirmReceipt")    public String confirmReceipt() {        logger.info("confirmReceipt确认收货..");        Account acc = getLoginAccount();        if (acc == null || StringUtils.isBlank(acc.getAccount())) {            return page_toLoginRedirect;        }        String orderid = RequestHolder.getRequest().getParameter("orderid");        if (StringUtils.isBlank(orderid)) {            throw new NullPointerException("参数异常！");        }		/*         * 用户可以对每个订单项对应的商品进行评价		 */        Orderlog orderlog = new Orderlog();        orderlog.setOrderid(orderid);        orderlog.setAccount(acc.getId());        orderlog.setContent("【交易完成】");        orderlog.setAccountType(Orderlog.orderlog_accountType_w);        orderlog.setStatus(Orderlog.operate_status_c);//确认收货        orderService.updateOrderStatusByConfirm(orderlog);        return "redirect:/account/orders";    }    /**     * 取消订单     * jiangyongzhi     *     * @return     */    @RequestMapping("delOrder")    public String delOrder(ModelMap model, RedirectAttributes flushAttrs) throws Exception {        logger.info("取消订单delOrder...");        Account acc = LoginUserHolder.getLoginAccount();        if (acc == null || StringUtils.isBlank(acc.getAccount())) {            return page_toLoginRedirect;        }        String orderid = RequestHolder.getRequest().getParameter("orderid");        if (StringUtils.isBlank(orderid)) {            throw new NullPointerException("参数异常！");        }        Order param = new Order();        param.setAccount(acc.getId());        param.setId(orderid);        List<Order> od = orderService.selectOrderInfo(param);        if (od != null && od.size() > 0) {            //用户可以对每个订单项对应的商品进行评价            Orderlog orderlog = new Orderlog();            orderlog.setOrderid(orderid);            orderlog.setAccount(acc.getId());            orderlog.setContent("【取消订单】用户已取消订单");            orderlog.setAccountType(Orderlog.orderlog_accountType_w);            orderlog.setStatus(Orderlog.operate_status_q);//取消订单            orderService.updateOrderStatusByConfirm(orderlog);            //恢复商品库存            ProductStock ps = new ProductStock();            ps.setProductID(od.get(0).getProductID());            ps.setProductBuyNumber(od.get(0).getNumber());            orderService.addProductStock(ps);        } else {            throw new NullPointerException("订单不存在！");        }        flushAttrs.addFlashAttribute("orderCancel", "订单已取消！");        return "redirect:/account/orders";    }    /**     * 快递费计算     */    @RequestMapping("getShiping")    public void getShiping(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception {        response.setContentType("application/xml;charset=utf-8");        PrintWriter out = response.getWriter();        //获取前台传递的子订单号        String orderCodeView = request.getParameter("id");        logger.info("orderCodeView from ftl is " + orderCodeView);        //获取前台传递的选中运送方式id        String shippingId = request.getParameter("shippingId");        //获取前台传递的选中地址id        String addressId = request.getParameter("addressId");        //运费价格        double shipMoney = 0;        //得到登录用户的信息        Account account = LoginUserHolder.getLoginAccount();        //从redis中获取父订单        Order parentOrder = (Order) redisCacheProvider.get(account.getId() + "parentOrder");        logger.info("parentOrder.getOrderCodeView() = " + parentOrder.getOrderCodeView());        //取得父订单中子订单list        List<Order> orderList = parentOrder.getOrders();		 /*		  * 获得选中子订单信息		  * 遍历父订单获取的所有子订单，与前台传递的子订单号比较		  * 若相等，则匹配上子订单		  */        Order order = new Order();        for (int i = 0; i < orderList.size(); i++) {            Order o = orderList.get(i);            logger.info("son orderCodeView is " + o.getOrderCodeView());            if (o.getOrderCodeView().equals(orderCodeView)) {                order = o;                break;            }        }        logger.info("选中的子订单号为：" + order.getOrderCode());        //获得选中快递方式信息        List<BusinessShipping> shipList = order.getBusinessShippingList();        //logger.info("shipList.size() = " + shipList.size());        BusinessShipping shipping = new BusinessShipping();        for (int i = 0; i < shipList.size(); i++) {            BusinessShipping s = shipList.get(i);            if (s.getShippingId().equals(shippingId)) {                shipping = s;                break;            }        }        logger.info("选中的快递为：" + shipping.getId());        //获得选中运送地址        Address address = addressService.selectById(addressId);        logger.info("address.getProvince() = " + address.getProvince());        //获得运费详情  用于计算        BusinessShippingDetail businessShippingDetail = new BusinessShippingDetail();        List<BusinessShippingDetail> shipdetailList = shipping.getBsdList();        logger.info("shipdetailList.size() = " + shipdetailList.size());        for (BusinessShippingDetail shippingDetail : shipdetailList) {            logger.info("shippingDetail.getProvinceId() = " + shippingDetail.getProvinceId());            if (shippingDetail.getProvinceId().equals(address.getProvince())) {                businessShippingDetail = shippingDetail;            }        }		 /*		  * 如果运送方式不支持客户选中地址，则直接返回0运费		  */        if (StringUtils.isNotBlank(businessShippingDetail.getId())) {            logger.info("businessShippingDetail.getId() = " + businessShippingDetail.getId());            logger.info("businessShippingDetail's info is " +                    businessShippingDetail.getBusinessShippingId() + " && " + businessShippingDetail.getFirstHeavy());            //商品所有重量            double productWeight = 0;            List<Orderdetail> OrderdetailList = order.getOrderdetail();            for (Orderdetail orderdetail : OrderdetailList) {                double pw = 0;                if (orderdetail.getProductWeight() != null && orderdetail.getProductWeight() != "") {                    pw = Double.parseDouble(orderdetail.getProductWeight()); //单个商品重量                }                double pCnt = orderdetail.getNumber();  //商品数量                productWeight = productWeight + pw * pCnt;            }            //商品重量向上取整            //		int productW = (int) Math.ceil(productWeight);            double firstHeavy = Double.parseDouble(businessShippingDetail.getFirstHeavy());//商品首重            if (productWeight <= firstHeavy) {                //商品重量小于等于首重。价格取首重价格                shipMoney = businessShippingDetail.getFristPrice();            } else {                double weight = productWeight - firstHeavy;                double setpHeavy = Double.parseDouble(businessShippingDetail.getStepHeavy());                double hmg = weight / setpHeavy; //快递规格                int cnt = (int) Math.ceil(hmg);                shipMoney = businessShippingDetail.getFristPrice();                shipMoney = shipMoney + cnt * businessShippingDetail.getStepPrice();            }            logger.info("shipMoney = " + shipMoney);            out.write(JsonUtil.objectToJson(String.valueOf(shipMoney)));        } else {            out.write(JsonUtil.objectToJson("noMatch"));        }    }    /**     * 查看指定订单的物流信息     */    @RequestMapping("qryApiStoreInfo")    @ResponseBody    public List<Map<String, Object>> qryApiStoreInfo() {        logger.info("qryApiStoreInfo查看物流");        String orderid = RequestHolder.getRequest().getParameter("orderid");        System.out.println("orderid:" + orderid);        if (StringUtils.isBlank(orderid)) {            throw new NullPointerException("参数异常！");        }        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();        ApiStoreInfo apiStoreInfo = ApiStore.request("YUNDA", "1201205716323");//orderid);        ApiStoreItem result = apiStoreInfo.getResult();        System.out.println("Msg:" + apiStoreInfo.getMsg());        System.out.println("status:" + apiStoreInfo.getStatus());        if (result != null) {            list = result.getList();            System.out.println("issign:" + result.getIssign());            for (Map<String, Object> map : list) {                System.out.println("time" + map.get("time"));                System.out.println("status" + map.get("status"));            }        }        return list;    }    public List<Map<String, Object>> qryApiStoreInfo(String orderid) {        System.out.println("orderid:");        logger.info("qryApiStoreInfo查看物流");        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();//			String orderid = RequestHolder.getRequest().getParameter("orderid");////			System.out.println("orderid:"+orderid);//			if(StringUtils.isBlank(orderid)){//				throw new NullPointerException("参数异常！");//			}        try {            ApiStoreInfo apiStoreInfo = ApiStore.request("YUNDA", orderid);            ApiStoreItem result = apiStoreInfo.getResult();            System.out.println("Msg:" + apiStoreInfo.getMsg());            System.out.println("status:" + apiStoreInfo.getStatus());            if (result != null) {                list = result.getList();                //				 System.out.println("issign:"+result.getIssign());                //				 for(Map<String,Object> map:list){                //					 System.out.println("time"+map.get("time"));                //					 System.out.println("status"+map.get("status"));                //				 }            }        } catch (Exception e) {            logger.error("订单编号：" + orderid + "， 当前查找不到物流信息：" + e.getMessage(), e);        }        return list;    }    /**     * 拦截404错误跳转页面     *     * @param model     * @return     * @throws Exception     */    @RequestMapping(value = "to404")    public String to404(ModelMap model) throws Exception {        logger.info("跳转404页面！");        return "404Ftl";    }    public Account getLoginAccount() {        HttpSession session = RequestHolder.getSession();        Account account = (Account) session.getAttribute(FrontContainer.USER_INFO);        if (account != null && StringUtils.isBlank(account.getId())) {            account.setId(account.getId());            session.setAttribute(FrontContainer.USER_INFO, account);        }        return session == null ? null : account;    }}